import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import Cookies from "js-cookie";

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['login', 'register', 'forget'] // no redirect whitelist

const nullVal = [null, undefined, NaN]

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  let hasUserToken = nullVal.indexOf(Cookies.get("user")) === -1
  // 用户已经登录
  if(hasUserToken) {
    if(whiteList.indexOf(to.name) === -1) {
      next()
    } else {
      next('/user/all')
    }
  } else {
    if(whiteList.indexOf(to.name) !== -1) {
      next()
    } else {
      next('/')
    }
  }
})

router.afterEach((to) => {
  // finish progress bar
  NProgress.done()
})
